import React, { useEffect, useState } from 'react'
import './index.css'
export default function Item({ todo, done, id, todoList, setTodoList }) {

    let [isActive, setIsActive] = useState(false)
    // // 鼠标移入函数
    // const MouseEventhandle = ()=>{
    //    setIsActive(true)
    // }
    // // 鼠标移出函数
    // const MouseLeavehandle = ()=>{
    //     setIsActive(false)
    // }

    const Mousehandle = (bool) => {
        return () => {
            setIsActive(bool)
        }

    }
    const changeCheckhandle = () => {
        /* 
        forEach不影响原数组
        如果执行if中的语句 相当于改变原来的TodoList
        map会映射出一个新的数组 所以可以直接赋值给一个变量
        let arr = todoList.map(item => {
            if (item.id === id) {
                item.done = !item.done
            }
           return item
        })
        
        setTodoList(arr)//【todoList】

        */

        todoList.forEach(item => {
            if (item.id === id) {
                item.done = !item.done
            }
        })
        let arr=[...todoList]
        console.log(todoList);
        setTodoList(arr)//【todoList】

    }

    const deleteMsghandle = ()=>{
       const num= todoList.findIndex((item)=>{
            return item.id === id
        })
        let arr = [...todoList]
       arr.splice(num,1)
       console.log(arr,todoList);

        // console.log(id);
        //slice
      // let arr = todoList.filter((item)=>item.id != id)
        setTodoList(arr)
    }

    return (
        <div>
            <li onMouseEnter={Mousehandle(true)} onMouseLeave={Mousehandle(false)} className={isActive ? 'active' : ''}>
                <label>
                    <input type="checkbox" checked={done} onChange={changeCheckhandle} />
                    <span>{todo}</span>
                </label>
                <button className="btn btn-danger" onClick={deleteMsghandle} style={{ display: isActive ? 'block' : 'none' }}>删除</button>
            </li>
        </div>
    )
}
